import pyautogui,time
import tkinter,cv2,PIL,numpy
from PIL import Image,ImageDraw,ImageFont,ImageGrab
import cv2
import time
import numpy as np
import os

from skimage.measure import compare_ssim
import cv2

class CompareImage():

    def compare_image(self, path_image1, path_image2):

        imageA = cv2.imread(path_image1)
        imageB = cv2.imread(path_image2)

        grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
        grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)

        (score, diff) = compare_ssim(grayA, grayB, full=True)
        #print("SSIM: {}".format(score))
        return score

def find_pic(pic,i):
    if i==0:
        #break
        return 800,800
    else:
   
        button7location = pyautogui.locateOnScreen(pic, confidence=0.8)
        try:
            x,y,w,h=button7location
            print("找到了{}".format(pic),x,y,w,h)
    #print(x,y,w,h)
            pyautogui.moveTo(x, y)
            return x,y
        except:
            time.sleep(0.5)
            print('未找到{}再试一次'.format(pic))
            return find_pic(pic,i-1)

       




def dragx(pic):
    img1=cv2.imread(pic)
    img2=cv2.imread('roi.png')
    err = cv2.absdiff(img1,img2)
    blur = cv2.blur(err,(5,5))
    gray = cv2.cvtColor(blur,cv2.COLOR_BGR2GRAY)
    ret,thresh1 = cv2.threshold(gray,20,255,cv2.THRESH_BINARY)
    kernel = np.ones((8,8),np.uint8)
    opening = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, kernel)
    contours,hierarchy = cv2.findContours(opening, 1, 2)

   
    for i in range(len(contours)):
       
        area = cv2.contourArea(contours[i])
        if area >2000:
            t=i
            break
        else:
            t=0
        print('hello:',area)
    print('t:',t)
    cnt = contours[t]
    x,y,w,h=cv2.boundingRect(cnt)
    print(x,y,w,h)
    #
    #box = cv2.boxPoints(rect)
    #box = np.int0(box)
    im=cv2.rectangle(img2, (x, y), (x+w, y+h), (0,0,255), 2)
    #im = cv2.rectangle(img2,(x,y),(x+w,y+h),0,(0,0,255),2)
    #这里要调整
    z=0
    if x>150:
        z=5
    elif x<50:
        z=-5
    elif x<70:
        z=-2
    elif x>120:
        z=3
    drag0=int(x)+85+z
    #print('rect:------',rect[0][0])
    #cv2.imshow('err',im)
    #cv2.imshow('opening',opening)
     
    #cv2.waitKey(5000)
    #cv2.destroyAllWindows()
    find_pic('drag.png',10)
    pyautogui.drag(drag0, 0, 0.6, button='left')
    time.sleep(0.5)

def compare(x,y):
    im = ImageGrab.grab()
    img=numpy.array(im)
    img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    #cv2.imshow('hello',img)
    #global x,y
    roi=img[y-190:y-30,x-40:x+220]
    compare_image = CompareImage()
    cv2.imwrite('roi.png',roi)
    
    city1=compare_image.compare_image('roi.png', "city.png")
    city2=compare_image.compare_image('roi.png', "city2.png")
    #rmw=compare_image.compare_image('roi.png', "rmw.png")
    print("city1:",city1,'city2',city2)
    if city2>0.5 or city1>0.5:
        return True
    else:
        return False

def compare1(x,y):
    im = ImageGrab.grab()
    img=numpy.array(im)
    img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    #cv2.imshow('hello',img)
    #global x,y
    roi=img[y-190:y-30,x-40:x+220]
    compare_image = CompareImage()
    cv2.imwrite('roi.png',roi)
    
    city1=compare_image.compare_image('roi.png', "city.png")
    city2=compare_image.compare_image('roi.png', "city2.png")
    #rmw=compare_image.compare_image('roi.png', "rmw.png")
    if city1>0.5:
        return 'city.png'
    else:
        return 'city2.png'


def one_time():

    find_pic('GD.png',10)

    pyautogui.move(100,50)
    pyautogui.click()
    x,y=find_pic('start0.png',10)
    print(x,y)
    pyautogui.click()
    time.sleep(1)
    im = ImageGrab.grab()
    img=numpy.array(im)
    img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    #cv2.imshow('hello',img)
    roi=img[y-190:y-30,x-40:x+220]
    #cv2.imshow('roi',roi)
    cv2.imwrite(str(time.time())+'.png',roi)
    find_pic('X.png',10)
    pyautogui.click()
   
def work1():
    x,y=find_pic('GD.png',10)
    if x==800:
        return False
    pyautogui.move(100,50)
    pyautogui.click()
    x,y=find_pic('start0.png',10)
    if x==800:
        return False
    #print(x,y)
    #pyautogui.click()
    time.sleep(0.5)
    #这里要调整
    pyautogui.move(205,-180)
    while not compare(x,y):
       
        pyautogui.click()
        time.sleep(0.3)
    pic=compare1(x,y)
    dragx(pic)
    x,y=find_pic('vote.png',10)
    if x==800:
        return False
    pyautogui.click()
    time.sleep(3)
    pyautogui.press('enter')
    time.sleep(1)
    return True
    #pyautogui.press('f5')
    #time.sleep(2)
   



def startx():
    os.system(r'taskkill /F /IM "chrome.exe"')
    time.sleep(2)

    os.system('start chrome')
    time.sleep(2)
    #pyautogui.hotkey('alt', 'f4')
    #time.sleep(2)
    pyautogui.hotkey('shift', 'ctrl','N')
    time.sleep(1)
    pyautogui.hotkey('shift')
    time.sleep(1)
    pyautogui.write(r'http://bj.people.com.cn/GB/25527/397922/index.html')
    #pyautogui.hotkey('ctrl','v')
    time.sleep(1)
    pyautogui.hotkey('enter')
    time.sleep(1)
    pyautogui.hotkey('enter')
    time.sleep(1)
    pyautogui.hotkey('F11')
    time.sleep(1)
    pyautogui.hotkey('end')

def main():

    startx()

    for j in range(50000):
        for i in range(10):
            work1()
       
        #time.sleep(1)
        
        #pyautogui.hotkey('alt', 'f4')
        #time.sleep(3)
        startx()
main()

